<template>
  <view>
    <!-- 搜索模块 -->
    <ugo-search></ugo-search>
    <!-- 主体区域 -->
    <view class="m-category">
      <scroll-view scroll-y class="left">
        <view class="item"
         v-for="(item, index) in cateLeft"
         :key="item.cat_id"
         :class="{ active: activeIndex === index }"
         @click="changeActiveIndex(index)">{{ item.cat_name }}</view>
      </scroll-view>
      <scroll-view scroll-y class="right">
        <view class="cate" v-for="item in cateRight" :key="item.cat_id">
          <view class="title">{{ item.cat_name }}</view>
          <view class="goods-list">
            <navigator class="goods" v-for="goods in item.children" :key="goods.cat_id"
            :url="`/pages/goods_list/index?query=${goods.cat_name}&cid=${goods.cat_id}`">
              <image :src="goods.cat_icon"
                class="pic" mode="aspectFit" />
              <view class="name">{{ goods.cat_name }}</view>
            </navigator>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      //分类列表
      cateList: [],
      //当前选中的分类的下标
      activeIndex:0,
      scrollTop:0,
    }
  },
  onLoad() {
    //调用
    this.getCateList()
  },
  methods: {
    //获取分类列表
    async getCateList() {
      const res = await uni.$u.http.get('/categories')
      this.cateList = res.data.message
    },
    //更改选中分类
    changeActiveIndex(index){
      this.activeIndex = index
      // 将其重置为-1，然后再下一次更新时重置为0，这样scroll-view就能每次都监测到变化
      this.scrollTop = -1;
      this.$nextTick(() => {
        this.scrollTop = 0;
      });
    }
  },
  computed: {
    cateLeft() {
      return this.cateList.map((item) => {
        return {
          cat_id: item.cat_id,
          cat_name: item.cat_name,
        }
      })
    },
    cateRight(){
      return this.cateList.length>0 ? this.cateList[this.activeIndex].children:[]
    }
  }
};
</script>

<style lang="scss">
.m-category {
  display: flex;
  height: calc(100vh - 20rpx - 34px);

  .left {
    height: 100%;
    width: 182rpx;
    font-size: 28rpx;
    text-align: center;
    background-color: #F3F3F3;

    .item {
      padding: 17rpx 0;

      &.active {
        background: #fff;
        color: #ea4350;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          width: 4rpx;
          height: 44rpx;
          background: #ea4350;
        }
      }
    }
  }

  .right {
    height: 100%;
    flex: 1;

    .title {
      margin: 18rpx 0 21rpx;
      text-align: center;
    }
  }
}

.goods-list {
  display: flex;
  padding: 0 48rpx;
  justify-content: space-between;
  flex-wrap: wrap;

  .pic {
    width: 120rpx;
    height: 120rpx;
  }

  .name {
    margin-bottom: 30rpx;
    font-size: 21rpx;
    color: #2E2E2E;
    text-align: center;
    line-height: 1;
  }
}
</style>
